﻿// <copyright file="RawDEXMLDAL.cs" company="The MITRE Corporation">
//    Copyright (c) 2010 The MITRE Corporation. All rights reserved.
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
//    http://www.apache.org/licenses/LICENSE-2.0
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.
// </copyright>

/////////////////////////////////////////////////////////////////////////////////////////////////
// RawDEXMLDAL.cs - Data Access Layer for Exposing Raw DEXML
// Project: IC.NETSOA- IC.NETDAL
//
// Language:    C#, .NET 4.0
// Platform:    Dell XPS m1530 Windows 7, VS 2010
// Author:      Don McGarry MITRE Rome
/////////////////////////////////////////////////////////////////////////////////////////////////

// Copyright (c) 2010 The MITRE Corporation. All rights reserved.
//
// NOTICE
// This software was produced for the U. S. Government
// under Contract No. FA8721-09-C-0001, and is
// subject to the Rights in Noncommercial Computer Software
// and Noncommercial Computer Software Documentation Clause
// (DFARS) 252.227-7014 (JUN 1995)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using ICNETServices;

namespace ICNETDAL
{
  /// <summary>
  /// This class contians the methods that deal with exposing XML and DEXML. 
  /// </summary>
  public static class RawDEXMLDAL
  {
    #region public methods

    /// <summary>
    /// GetAllDEXML returns a list of XML elements representing all of the current DEs' XML
    /// </summary>
    /// <returns>List of XML Elements</returns>
    public static List<XElement> GetAllDEXML()
    {
      List<XElement> mylist = new List<XElement>(); // create a list of xml elements
      XNamespace xs = ICNETSOAConstants.ICNETbaseURI;
      EDXLSQLDataContext linQDB = new EDXLSQLDataContext(ICNETSOAConstants.ICNETConnectionString);  // get the data for the connection
      var mainobjects = from emContainer in linQDB.EmergencyMessageContainers                       // get all of the entries in the EmergencyMessageContainer table
                        orderby emContainer.DateTimeSent // ordered by sent
                        select emContainer;
      //// for each entry in the EmergencyMessageContainer table
      ////add its raw xml element to the list of elements to return
      foreach (EmergencyMessageContainer mainobj in mainobjects)
      {   
        mylist.Add(mainobj.DEXML);                                                             
      }

      return mylist;
    }

    /// <summary>
    /// GetAllDEXML returns a list of XML elements representing all of the current DEs' XML
    /// </summary>
    /// <returns>List of XML Elements</returns>
    public static List<XElement> GetActiveDEXML()
    {
      List<XElement> mylist = new List<XElement>(); // create a list of xml elements
      XNamespace xs = ICNETSOAConstants.ICNETbaseURI;
      EDXLSQLDataContext linQDB = new EDXLSQLDataContext(ICNETSOAConstants.ICNETConnectionString);  // get the data for the connection

      var exposureCaches = from p in linQDB.ExposureCaches
                           where p.ExpirationTime > DateTime.UtcNow
                           orderby p.PublishDate descending
                           select p;

      var contentobjects = from emContent in linQDB.EmergencyMessageContents
                           join expCache in exposureCaches on emContent.Id equals expCache.EmergencyMessageContentId
                           orderby expCache.LastUpdatedTime
                           select emContent;

      var mainobjects = from emContainer in linQDB.EmergencyMessageContainers                       // get all of the entries in the EmergencyMessageContainer table
                        join content in contentobjects on emContainer.Id equals content.EmergencyMessageContainerId
                        orderby emContainer.DateTimeSent // ordered by sent
                        select emContainer;
      
      //// for each entry in the EmergencyMessageContainer table
      ////add its raw xml element to the list of elements to return
      foreach (EmergencyMessageContainer mainobj in mainobjects)
      {
        mylist.Add(mainobj.DEXML);
      }

      return mylist;
    }

    /// <summary>
    /// GetAllDEXML returns a list of XML elements representing all of the current DEs' XML
    /// </summary>
    /// <returns>List of XML Elements</returns>
    public static List<XElement> GetExpiredDEXML()
    {
      List<XElement> mylist = new List<XElement>(); // create a list of xml elements
      XNamespace xs = ICNETSOAConstants.ICNETbaseURI;
      EDXLSQLDataContext linQDB = new EDXLSQLDataContext(ICNETSOAConstants.ICNETConnectionString);  // get the data for the connection

      var exposureCaches = from p in linQDB.ExposureCaches
                           where p.ExpirationTime <= DateTime.UtcNow
                           orderby p.PublishDate descending
                           select p;

      var contentobjects = from emContent in linQDB.EmergencyMessageContents
                           join expCache in exposureCaches on emContent.Id equals expCache.EmergencyMessageContentId
                           orderby expCache.LastUpdatedTime
                           select emContent;

      var mainobjects = from emContainer in linQDB.EmergencyMessageContainers                       // get all of the entries in the EmergencyMessageContainer table
                        join content in contentobjects on emContainer.Id equals content.EmergencyMessageContainerId
                        orderby emContainer.DateTimeSent // ordered by sent
                        select emContainer;

      //// for each entry in the EmergencyMessageContainer table
      ////add its raw xml element to the list of elements to return
      foreach (EmergencyMessageContainer mainobj in mainobjects)
      {
        mylist.Add(mainobj.DEXML);
      }

      return mylist;
    }

    /// <summary>
    /// GetAllDEXML returns a list of XML elements representing all of the current DEs' XML
    /// </summary>
    /// <returns>List of XML Elements</returns>
    public static List<XElement> GetUpdatedDEXML(DateTime Since)
    {
      List<XElement> mylist = new List<XElement>(); // create a list of xml elements
      XNamespace xs = ICNETSOAConstants.ICNETbaseURI;
      EDXLSQLDataContext linQDB = new EDXLSQLDataContext(ICNETSOAConstants.ICNETConnectionString);  // get the data for the connection

      var exposureCaches = from p in linQDB.ExposureCaches
                           where p.LastUpdatedTime >= Since.ToUniversalTime()
                           orderby p.PublishDate descending
                           select p;

      var contentobjects = from emContent in linQDB.EmergencyMessageContents
                           join expCache in exposureCaches on emContent.Id equals expCache.EmergencyMessageContentId
                           orderby expCache.LastUpdatedTime
                           select emContent;

      var mainobjects = from emContainer in linQDB.EmergencyMessageContainers                       // get all of the entries in the EmergencyMessageContainer table
                        join content in contentobjects on emContainer.Id equals content.EmergencyMessageContainerId
                        orderby emContainer.DateTimeSent // ordered by sent
                        select emContainer;

      //// for each entry in the EmergencyMessageContainer table
      ////add its raw xml element to the list of elements to return
      foreach (EmergencyMessageContainer mainobj in mainobjects)
      {
        mylist.Add(mainobj.DEXML);
      }

      return mylist;
    }

    /// <summary>
    /// GetAllDEXML returns a list of XML elements representing all of the current DEs' keys
    /// </summary>
    /// <returns>List of XML Elements</returns>
    public static List<XElement> GetAllDELink()
    {
      List<XElement> mylist = new List<XElement>(); // create a list of xml elements
      XNamespace xs = ICNETSOAConstants.ICNETbaseURI;
      EDXLSQLDataContext linQDB = new EDXLSQLDataContext(ICNETSOAConstants.ICNETConnectionString);  // get the data for the connection
      var mainobjects = from emContainer in linQDB.EmergencyMessageContainers                       // get all of the entries in the EmergencyMessageContainer table
                        orderby emContainer.DateTimeSent // ordered by sent
                        select emContainer;
      //// for each entry in the EmergencyMessageContainer table
      ////add its raw xml element to the list of elements to return
      foreach (EmergencyMessageContainer entry in mainobjects)
      {
        XElement deKey = new XElement("DELink");

        deKey.Add(new XElement("distributionID", entry.DistributionCode));
        deKey.Add(new XElement("senderID", entry.SenderCode));
        deKey.Add(new XElement("dateTimeSent", entry.DateTimeSent.ToLocalTime().ToString("yyyy-MM-ddThh:mm:sszzz")));
        
        foreach (EmergencyMessageContent content in entry.EmergencyMessageContents)
        {
          XElement contentKey = new XElement("contentObject");
          if (content.Type.StartsWith("XML"))
          {
            contentKey.Add(new XElement("Link", ICNETSOAConstants.ICNETdatalinkToHTML + content.DSCHash.ToString()));
          }
          else
          {
            if (!string.IsNullOrWhiteSpace(content.NonXMLContents[0].Uri))
            {
              contentKey.Add(new XElement("Link", content.NonXMLContents[0].Uri));
            }
            else
            {
              contentKey.Add(new XElement("Link", ICNETSOAConstants.ICNETdatalinkToMIME + content.DSCHash.ToString()));
            }
          }
          deKey.Add(contentKey);
        }

        mylist.Add(deKey);
      }

      return mylist;
    }

    /// <summary>
    /// GetAllDEXML returns a list of XML elements representing all of the current DEs' XML
    /// </summary>
    /// <returns>List of XML Elements</returns>
    public static List<XElement> GetActiveDELink()
    {
      List<XElement> mylist = new List<XElement>(); // create a list of xml elements
      XNamespace xs = ICNETSOAConstants.ICNETbaseURI;
      EDXLSQLDataContext linQDB = new EDXLSQLDataContext(ICNETSOAConstants.ICNETConnectionString);  // get the data for the connection

      var exposureCaches = from p in linQDB.ExposureCaches
                           where p.ExpirationTime > DateTime.UtcNow
                           orderby p.PublishDate descending
                           select p;

      var contentobjects = from emContent in linQDB.EmergencyMessageContents
                           join expCache in exposureCaches on emContent.Id equals expCache.EmergencyMessageContentId
                           orderby expCache.LastUpdatedTime
                           select emContent;

      var mainobjects = from emContainer in linQDB.EmergencyMessageContainers                       // get all of the entries in the EmergencyMessageContainer table
                        join content in contentobjects on emContainer.Id equals content.EmergencyMessageContainerId
                        orderby emContainer.DateTimeSent // ordered by sent
                        select emContainer;

      //// for each entry in the EmergencyMessageContainer table
      ////add its raw xml element to the list of elements to return
      foreach (EmergencyMessageContainer entry in mainobjects)
      {
        XElement deKey = new XElement("DELink");

        deKey.Add(new XElement("distributionID", entry.DistributionCode));
        deKey.Add(new XElement("senderID", entry.SenderCode));
        deKey.Add(new XElement("dateTimeSent", entry.DateTimeSent.ToLocalTime().ToString("yyyy-MM-ddThh:mm:sszzz")));

        foreach (EmergencyMessageContent content in entry.EmergencyMessageContents)
        {
          XElement contentKey = new XElement("contentObject");
          if (content.Type.StartsWith("XML"))
          {
            contentKey.Add(new XElement("Link", ICNETSOAConstants.ICNETdatalinkToHTML + content.DSCHash.ToString()));
          }
          else
          {
            if (!string.IsNullOrWhiteSpace(content.NonXMLContents[0].Uri))
            {
              contentKey.Add(new XElement("Link", content.NonXMLContents[0].Uri));
            }
            else
            {
              contentKey.Add(new XElement("Link", ICNETSOAConstants.ICNETdatalinkToMIME + content.DSCHash.ToString()));
            }
          }
          deKey.Add(contentKey);
        }

        mylist.Add(deKey);
      }

      return mylist;
    }

    /// <summary>
    /// GetAllDEXML returns a list of XML elements representing all of the current DEs' XML
    /// </summary>
    /// <returns>List of XML Elements</returns>
    public static List<XElement> GetExpiredDELink()
    {
      List<XElement> mylist = new List<XElement>(); // create a list of xml elements
      XNamespace xs = ICNETSOAConstants.ICNETbaseURI;
      EDXLSQLDataContext linQDB = new EDXLSQLDataContext(ICNETSOAConstants.ICNETConnectionString);  // get the data for the connection

      var exposureCaches = from p in linQDB.ExposureCaches
                           where p.ExpirationTime <= DateTime.UtcNow
                           orderby p.PublishDate descending
                           select p;

      var contentobjects = from emContent in linQDB.EmergencyMessageContents
                           join expCache in exposureCaches on emContent.Id equals expCache.EmergencyMessageContentId
                           orderby expCache.LastUpdatedTime
                           select emContent;

      var mainobjects = from emContainer in linQDB.EmergencyMessageContainers                       // get all of the entries in the EmergencyMessageContainer table
                        join content in contentobjects on emContainer.Id equals content.EmergencyMessageContainerId
                        orderby emContainer.DateTimeSent // ordered by sent
                        select emContainer;

      //// for each entry in the EmergencyMessageContainer table
      ////add its raw xml element to the list of elements to return
      foreach (EmergencyMessageContainer entry in mainobjects)
      {
        XElement deKey = new XElement("DELink");

        deKey.Add(new XElement("distributionID", entry.DistributionCode));
        deKey.Add(new XElement("senderID", entry.SenderCode));
        deKey.Add(new XElement("dateTimeSent", entry.DateTimeSent.ToLocalTime().ToString("yyyy-MM-ddThh:mm:sszzz")));

        foreach (EmergencyMessageContent content in entry.EmergencyMessageContents)
        {
          XElement contentKey = new XElement("contentObject");
          if (content.Type.StartsWith("XML"))
          {
            contentKey.Add(new XElement("Link", ICNETSOAConstants.ICNETdatalinkToHTML + content.DSCHash.ToString()));
          }
          else
          {
            if (!string.IsNullOrWhiteSpace(content.NonXMLContents[0].Uri))
            {
              contentKey.Add(new XElement("Link", content.NonXMLContents[0].Uri));
            }
            else
            {
              contentKey.Add(new XElement("Link", ICNETSOAConstants.ICNETdatalinkToMIME + content.DSCHash.ToString()));
            }
          }
          deKey.Add(contentKey);
        }

        mylist.Add(deKey);
      }

      return mylist;
    }

    /// <summary>
    /// GetAllDEXML returns a list of XML elements representing all of the current DEs' XML
    /// </summary>
    /// <returns>List of XML Elements</returns>
    public static List<XElement> GetUpdatedDELink(DateTime Since)
    {
      List<XElement> mylist = new List<XElement>(); // create a list of xml elements
      XNamespace xs = ICNETSOAConstants.ICNETbaseURI;
      EDXLSQLDataContext linQDB = new EDXLSQLDataContext(ICNETSOAConstants.ICNETConnectionString);  // get the data for the connection

      var exposureCaches = from p in linQDB.ExposureCaches
                           where p.LastUpdatedTime >= Since.ToUniversalTime()
                           orderby p.PublishDate descending
                           select p;

      var contentobjects = from emContent in linQDB.EmergencyMessageContents
                           join expCache in exposureCaches on emContent.Id equals expCache.EmergencyMessageContentId
                           orderby expCache.LastUpdatedTime
                           select emContent;

      var mainobjects = from emContainer in linQDB.EmergencyMessageContainers                       // get all of the entries in the EmergencyMessageContainer table
                        join content in contentobjects on emContainer.Id equals content.EmergencyMessageContainerId
                        orderby emContainer.DateTimeSent // ordered by sent
                        select emContainer;

      //// for each entry in the EmergencyMessageContainer table
      ////add its raw xml element to the list of elements to return
      foreach (EmergencyMessageContainer entry in mainobjects)
      {
        XElement deKey = new XElement("DELink");

        deKey.Add(new XElement("distributionID", entry.DistributionCode));
        deKey.Add(new XElement("senderID", entry.SenderCode));
        deKey.Add(new XElement("dateTimeSent", entry.DateTimeSent.ToLocalTime().ToString("yyyy-MM-ddThh:mm:sszzz")));

        foreach (EmergencyMessageContent content in entry.EmergencyMessageContents)
        {
          XElement contentKey = new XElement("contentObject");
          if (content.Type.StartsWith("XML"))
          {
            contentKey.Add(new XElement("Link", ICNETSOAConstants.ICNETdatalinkToHTML + content.DSCHash.ToString()));
          }
          else
          {
            if (!string.IsNullOrWhiteSpace(content.NonXMLContents[0].Uri))
            {
              contentKey.Add(new XElement("Link", content.NonXMLContents[0].Uri));
            }
            else
            {
              contentKey.Add(new XElement("Link", ICNETSOAConstants.ICNETdatalinkToMIME + content.DSCHash.ToString()));
            }
          }
          deKey.Add(contentKey);
        }

        mylist.Add(deKey);
      }

      return mylist;
    }

    /// <summary>
    /// GetDEByRole returns a list of XML elements representing all fo the DE's keys that
    /// satisfies the supplied Role and RoleURI
    /// </summary>
    /// <param name="role">Role to query on</param>
    /// <param name="roleURI">RoleURI to query on</param>
    /// <returns>List of XML Elements</returns>
    public static List<XElement> GetDELinkByRole(string role, string roleURI)
    {
      List<XElement> mylist = new List<XElement>(); // create a list of xml elements
      EDXLSQLDataContext linQDB = new EDXLSQLDataContext(ICNETSOAConstants.ICNETConnectionString);
      //// var Headlines = from o in LinQDB.ExposureCacheRoles
      var distributionElementMains = from ecr in linQDB.ExposureCacheRoles
                    where ecr.ListURI == roleURI && ecr.Value == role
                    join ec in linQDB.ExposureCaches on ecr.ExposureCacheId equals ec.Id
                    join emcontent in linQDB.EmergencyMessageContents on ec.EmergencyMessageContentId equals emcontent.Id
                    join emcontainer in linQDB.EmergencyMessageContainers on emcontent.EmergencyMessageContainerId equals emcontainer.Id
                    orderby ec.PublishDate descending
                    select emcontainer;
                    //// select p;

      // var deContents = from o in Headlines
      //  join p in LinQDB.DEContentObjects on o.ContentKey equals p.ContentObjectKey
      //  select p;

      // var deMains = from o in deContents
      // join p in LinQDB.DEMains on o.DEKey equals p.DEKey
      //  select p;
      foreach (EmergencyMessageContainer entry in distributionElementMains)
      {
        XElement deKey = new XElement("DELink");

        deKey.Add(new XElement("distributionID", entry.DistributionCode));
        deKey.Add(new XElement("senderID", entry.SenderCode));
        deKey.Add(new XElement("dateTimeSent", entry.DateTimeSent.ToLocalTime().ToString("yyyy-MM-ddThh:mm:sszzz")));
        
        foreach (EmergencyMessageContent content in entry.EmergencyMessageContents)
        {
          XElement contentKey = new XElement("contentObject");

          if (content.Type.StartsWith("XML"))
          {
            contentKey.Add(new XElement("Link", ICNETSOAConstants.ICNETdatalinkToHTML + content.DSCHash.ToString()));
          }
          else
          {
            if (!string.IsNullOrWhiteSpace(content.NonXMLContents[0].Uri))
            {
              contentKey.Add(new XElement("Link", content.NonXMLContents[0].Uri));
            }
            else
            {
              contentKey.Add(new XElement("Link", ICNETSOAConstants.ICNETdatalinkToMIME + content.DSCHash.ToString()));
            }
          }
          deKey.Add(contentKey);
        }

        mylist.Add(deKey);
      }

      return mylist;
    }

    /// <summary>
    /// GetDEByRole returns a list of XML elements representing all fo the DE's XML that
    /// satisfies the supplied Role and RoleURI
    /// </summary>
    /// <param name="role">Role to query on</param>
    /// <param name="roleURI">RoleURI to query on</param>
    /// <returns>List of XML Elements</returns>
    public static List<XElement> GetDEByRole(string role, string roleURI)
    {
      List<XElement> mylist = new List<XElement>(); // create a list of xml elements
      EDXLSQLDataContext linQDB = new EDXLSQLDataContext(ICNETSOAConstants.ICNETConnectionString);
      //// var Headlines = from o in LinQDB.ExposureCacheRoles
      var distributionElementMains = from ecr in linQDB.ExposureCacheRoles
                                     where ecr.ListURI == roleURI && ecr.Value == role
                                     join ec in linQDB.ExposureCaches on ecr.ExposureCacheId equals ec.Id
                                     join emcontent in linQDB.EmergencyMessageContents on ec.EmergencyMessageContentId equals emcontent.Id
                                     join emcontainer in linQDB.EmergencyMessageContainers on emcontent.EmergencyMessageContainerId equals emcontainer.Id
                                     orderby ec.PublishDate descending
                                     select emcontainer;
      //// select p;

      // var deContents = from o in Headlines
      //  join p in LinQDB.DEContentObjects on o.ContentKey equals p.ContentObjectKey
      //  select p;

      // var deMains = from o in deContents
      // join p in LinQDB.DEMains on o.DEKey equals p.DEKey
      //  select p;
      foreach (EmergencyMessageContainer entry in distributionElementMains)
      {
        mylist.Add(entry.DEXML);
      }

      return mylist;
    }
    #endregion
  }
}

